using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using ExamPaperEditingSystem.Models;

namespace ExamPaperEditingSystem.Services
{
    public class EmbeddingService : IEmbeddingService
    {
        private readonly HttpClient _httpClient;
        private const string OnlineApiUrl = "http://50844s9656.wocp.fun:42440/v1/embeddings";
        private const string LocalApiUrl = "http://192.168.100.71:8001/v1/embeddings";

        public EmbeddingService()
        {
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(30);
        }

        public bool IsOnlineApiAvailable { get; private set; }
        public bool IsLocalApiAvailable { get; private set; }

        public async Task<float[]> GetEmbeddingAsync(string text, string? apiUrl = null)
        {
            var response = await GetEmbeddingResponseAsync(text, apiUrl);
            return response.Data.Count > 0 ? response.Data[0].Embedding : Array.Empty<float>();
        }

        public async Task<EmbeddingResponse> GetEmbeddingResponseAsync(string text, string? apiUrl = null)
        {
            // 优先使用指定的API，否则按优先级选择
            string targetUrl = apiUrl ?? await GetAvailableApiUrlAsync();
            
            var request = new EmbeddingRequest
            {
                Input = text,
                Model = "text-embedding-bge-m3"
            };

            var json = JsonSerializer.Serialize(request, new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            });

            var content = new StringContent(json, Encoding.UTF8, "application/json");

            try
            {
                var response = await _httpClient.PostAsync(targetUrl, content);
                response.EnsureSuccessStatusCode();

                var responseJson = await response.Content.ReadAsStringAsync();
                var embeddingResponse = JsonSerializer.Deserialize<EmbeddingResponse>(responseJson, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });

                return embeddingResponse ?? new EmbeddingResponse();
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"获取向量嵌入失败: {ex.Message}", ex);
            }
        }

        public async Task<bool> TestApiConnectionAsync(string apiUrl)
        {
            try
            {
                var testRequest = new EmbeddingRequest
                {
                    Input = "test",
                    Model = "text-embedding-bge-m3"
                };

                var json = JsonSerializer.Serialize(testRequest, new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
                });

                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await _httpClient.PostAsync(apiUrl, content);
                
                return response.IsSuccessStatusCode;
            }
            catch
            {
                return false;
            }
        }

        private async Task<string> GetAvailableApiUrlAsync()
        {
            // 首先测试本地API
            IsLocalApiAvailable = await TestApiConnectionAsync(LocalApiUrl);
            if (IsLocalApiAvailable)
            {
                return LocalApiUrl;
            }

            // 然后测试在线API
            IsOnlineApiAvailable = await TestApiConnectionAsync(OnlineApiUrl);
            if (IsOnlineApiAvailable)
            {
                return OnlineApiUrl;
            }

            throw new InvalidOperationException("没有可用的嵌入向量API服务");
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}